package com.dlc.shop.user.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.AllinpayBalanceOrderSuccessEvent;
import com.dlc.shop.bean.model.UserExtension;
import com.dlc.shop.common.allinpay.constant.PaySysType;
import com.dlc.shop.common.util.Arith;
import com.dlc.shop.service.PayInfoService;
import com.dlc.shop.service.UserExtensionService;
import com.dlc.shop.user.common.model.UserBalanceLog;
import com.dlc.shop.user.common.service.UserBalanceLogService;
import com.dlc.shop.user.common.service.UserLevelService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 余额支付操作
 *
 * @author lhd
 */
@Component("allinpayBalancePaySuccessListener")
@AllArgsConstructor
public class AllinpayBalancePaySuccessListener {

    private final UserBalanceLogService userBalanceLogService;

    private final PayInfoService payInfoService;

    private final UserExtensionService userExtensionService;

    private final UserLevelService userLevelService;

    @EventListener(AllinpayBalanceOrderSuccessEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void balanceListener(AllinpayBalanceOrderSuccessEvent event) {
        String payNo = event.getPayNo();
        Integer type = event.getType();
        String userId= event.getUserId();
        Double amount = event.getAmount();
        UserBalanceLog balanceLog = userBalanceLogService.getOne(new LambdaQueryWrapper<UserBalanceLog>()
                .eq(UserBalanceLog::getPayNo, payNo).eq(UserBalanceLog::getIsPayed,0).eq(UserBalanceLog::getPaySysType,PaySysType.ALLINPAY.value()));
        // 已经支付
        if (Objects.isNull(balanceLog)) {
            return;
        }
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, userId));
        if (Objects.isNull(userExtension)) {
            return;
        }
        userExtension.setAllinpayTotalBalance(Arith.sub(userExtension.getAllinpayTotalBalance(), amount));
        userExtension.setAllinpayBalance(Arith.sub(userExtension.getAllinpayBalance(), amount));
        userExtensionService.updateById(userExtension);
        UserBalanceLog userBalanceLog = new UserBalanceLog();
        userBalanceLog.setBalanceLogId(balanceLog.getBalanceLogId());
        userBalanceLog.setIsPayed(1);
        userBalanceLogService.updateById(userBalanceLog);
    }
}
